package openbang.account.service.util;

import java.util.logging.Logger;

import openbang.account.service.exception.SecurityOBException;
import openbang.account.service.vo.ExceptionEnum;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * GWT提供的 RemoteServiceServlet的 子类
 * 1.增加了统一的登录安全检查，如果调用该服务的Session没有登录，则自动抛出安全异常
 * 2.继承该类的服务的方法声明，都必须抛出： throws SecurityOBException
 *   
 * @author aibo zeng
 *
 */

@SuppressWarnings("serial")
public class SecurityRemoteServiceServlet extends RemoteServiceServlet {
	private static final Logger log = Logger.getLogger(SecurityRemoteServiceServlet.class.getName());
	
	@Override
	protected void onBeforeRequestDeserialized(String serializedRequest) {
		//if(!SessionHelper.getUserLoginInfo(getThreadLocalRequest()).isLogined()){
		//	log.warning("有黑客? ");
		//}
		//这里拦截,效率最高,但无法知道尝试调用的是哪一个服务
	}	
	
	@Override
	protected void onAfterRequestDeserialized(RPCRequest rpcRequest){
		//必须保证调用 RPC.invokeAndEncodeResponse 之前
		//if(!SessionHelper.getUserLoginInfo(getThreadLocalRequest()).isLogined()){
	    //    //取得 要调用的 action 类名 , 即 接口名 
	    //    String actionName = rpcRequest.getMethod().getDeclaringClass().getName();
		//	log.warning("有黑客? class ="+actionName+",method="+rpcRequest.getMethod());
		//	无法抛出异常 throw new SecurityOBException(); 只好 拦截  processCall()方法
		//}		
	}

	@Override
	public String processCall(String payload) throws SerializationException {
	    try {
	      RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
	      
	      //2010-02-05 添加拦截- begin
		  if(!SessionHelper.getUserLoginInfo(getThreadLocalRequest()).isLogined()){
		      //取得 要调用的 action 类名 , 即 接口名 
		      String actionName = rpcRequest.getMethod().getDeclaringClass().getName();
			  log.warning("有黑客? class ="+actionName+",method="+rpcRequest.getMethod());
			  throw new SecurityOBException(ExceptionEnum.NOT_LOGIN.getCode());
		  }		
	      //2010-02-05 添加拦截 - end
		  
	      onAfterRequestDeserialized(rpcRequest);
	      return RPC.invokeAndEncodeResponse(this, rpcRequest.getMethod(),
	          rpcRequest.getParameters(), rpcRequest.getSerializationPolicy(),
	          rpcRequest.getFlags());
	    } catch (IncompatibleRemoteServiceException ex) {
	      log(
	          "An IncompatibleRemoteServiceException was thrown while processing this call.",
	          ex);
	      return RPC.encodeResponseForFailure(null, ex);
	    }
	  }		
}
